﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using LevenBlog.Core.Data;
using LevenBlog.Core.Entities;
using LevenBlog.Core.Utils;
using LevenBlog.Core.Service;

namespace LevenBlog.Core.User
{
    public class AdminMembership : UserMembership
    {
        private static string adminCookieName = WebConfig.PrefixKey + "LevenBlogAdminCookie";

        protected override string CookieName
        {
            get
            {
                return adminCookieName;
            }
        }

        public override void Write(DateTime expressTime)
        {
            //base.Write();
            HttpCookie cookie = new HttpCookie(CookieName);
            lb_user user = new lb_user();
            user.id = User.id;
            user.name = User.name;
            user.password = User.password;
            user.postnum = User.postnum;
            user.typeid = User.typeid;
            cookie.Value = SecurityCookie.EncryptToBase64(user, WebConfig.AdminPasswordKey);
            if (expressTime != DateTime.MaxValue && expressTime != DateTime.MinValue)
            {
                cookie.Expires = expressTime;
            }
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public override void Write()
        {
            this.Write(DateTime.MaxValue);
        }

        public override void Read()
        {
            //base.Read();
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(CookieName);
            if (cookie == null)
            {
                User = BlogUser.Default(Provider);
                User.usertype = UserType.GetDefault(Provider);
            }
            else
            {
                CookieString = cookie.Value;
                User = SecurityCookie.DecryptFromBase64(cookie.Value, WebConfig.AdminPasswordKey);
                User.usertype = UserType.Get(Provider, User.typeid);
                if (User.usertype == null)
                    throw new Exception("无法获取用户的权限信息.");
            }
            try
            {
                Authority.Fill(User.usertype.competence);
            }
            catch (Exception e)
            {
                throw new Exception("无法将数据库中的权限数据转换为数据实体", e);
            }
        }
    }
}
